package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.config.MyBloomConfig;
import org.example.entity.Access;
import org.example.service.IAccessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2023-05-07
 */
@RestController
@RequestMapping("/access")
public class AccessController {
    @Autowired
    private IAccessService accessService;
    @Autowired
    private MyBloomConfig myBloomConfig;

    @GetMapping
    public Page<Access> getAll(Access access, int pageNo, int pageSize){

//        QueryWrapper queryWrapper= Wrappers.query()
//                .like(StringUtils.hasText(access.getPrincipal()),"principal",access.getPrincipal())
//                .eq(access.getHospitalId()!=null,"hospital_id",access.getHospitalId());

        LambdaQueryWrapper<Access> queryWrapper = Wrappers.lambdaQuery(Access.class)
                .like(StringUtils.hasText(access.getPrincipal()),Access::getPrincipal,access.getPrincipal())
                .eq(access.getHospitalId()!=null,Access::getHospitalId,access.getHospitalId());
        return accessService.page(Page.of(pageNo,pageSize),queryWrapper);
    }

    @GetMapping("/{id}")
    public Access get(@PathVariable Long id){
        if(myBloomConfig.bloomFilter.mightContain(id)){
            System.out.println("id为"+id+"的book在数据库中存在");
            return accessService.getById(id);
        }else {
            System.out.println("id为"+id+"的book在数据库中不存在");
            return null;
        }
    }

    @PostMapping
    public Access add(@RequestBody Access access){
        return accessService.saveWithCache(access);
    }

    @DeleteMapping("/{id}")
    public boolean del(@PathVariable Long id){
        return accessService.removeById(id);
    }

    @PutMapping
    public Access update(@RequestBody Access access){
        return accessService.updateByIdwithCache(access);
    }
}
